package models

import (
	"gorm.io/gorm"
	"video-srv/basic/config"
)

// 视频表
type Video struct {
	gorm.Model
	UserId    int    `gorm:"type:int;comment:'用户id'"`
	Title     string `gorm:"type:varchar(50);comment:'标题'"`
	Desc      string `gorm:"type:varchar(255);comment:'描述'"`
	TypeId    int    `gorm:"type:int;comment:分类id"`
	CoverUrl  string `gorm:"type:varchar(300);comment:'封面url'"`
	LookCount int    `gorm:"type:int;default:0;comment:'观看数'"`
	LikeCount int    `gorm:"type:int;default:0;comment:'点赞数'"`
}

func (v *Video) TableName() string {
	return "video"
}

// 发布视频
func (v *Video) AddVideo(db *gorm.DB) error {
	return db.Debug().Create(&v).Error
}

// 视频列表
func (v *Video) GetVideoList(page, pageSize int, typeId int64) (videoList []*Video, err error) {
	offset := (page - 1) * pageSize
	db := config.DB
	if typeId > 0 {
		db = db.Where("type_id = ?", typeId)
	}
	if page > 0 || pageSize > 0 {
		db = db.Offset(offset).Limit(pageSize)
	}

	db.Joins("join checks on checks.video_id =video.id").Where("checks.status=1").Find(&videoList)
	return videoList, err

}

// 视频详情
func (v *Video) GetVideoDetail(db *gorm.DB, id int64) error {
	return db.Model(&Video{}).Debug().
		Select("video.user_id,video.title as title,video.desc,video.cover_url,checks.status,video.like_count").
		Joins("join checks on checks.video_id = video.id").
		Where("video.id = ?", id).Find(&v).Error
}

// 通过id查询视频
func (v *Video) GetVideoById(db *gorm.DB, id int64) error {
	return db.Model(&Video{}).Where("id = ?", id).Limit(1).Find(&v).Error
}

// 更新视频观看数
func (v *Video) UpdateVideoLookCount(db *gorm.DB, id int64) error {
	return db.Model(&Video{}).Where("id = ?", id).Update("look_count", gorm.Expr("look_count + ?", 1)).Find(&v).Error

}

// 更新视频点赞量
func (v *Video) UpdateVideoLikeCount(db *gorm.DB, id int64) error {
	return db.Model(&Video{}).Where("id = ?", id).Update("like_count", gorm.Expr("like_count + ?", 1)).Find(&v).Error
}

// 取消视频点赞
func (v *Video) DelVideoLikeCount(db *gorm.DB, id int64) error {
	return db.Model(&Video{}).Where("id = ?", id).Update("like_count", gorm.Expr("like_count - ?", 1)).Find(&v).Error
}

// 查询视频点赞总数
func (v *Video) GetVideoLikeCount(db *gorm.DB, id int64) error {
	return db.Model(&User{}).Debug().
		Select("like_count").Group("like_count").
		Where("id = ?", id).Find(&v).Error
}
